package com.ynding.common.easypoi.model;

import cn.hutool.core.util.StrUtil;
import org.apache.xmlgraphics.util.UnitConv;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.*;

/**
 * barcode4j条码工具类
 *
 * @author ynding
 */
public class Barcode4jUtil {
    /**
     * 生成条码，并保存到文件
     *
     * @param msg  条码信息
     * @param path 文件路径
     * @return
     */
    public static File generateFile(String msg, String path) {
        File file = new File(path);
        try {
            generate(msg, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return file;
    }

    /**
     * 生成字节
     *
     * @param msg
     * @return
     */
    public static byte[] generate(String msg) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        generate(msg, ous);
        return ous.toByteArray();
    }

    /**
     * 生成条码，保存到流
     *
     * @param msg
     * @param ous
     */
    public static void generate(String msg, OutputStream ous) {
        if (StrUtil.isEmpty(msg) || ous == null) {
            return;
        }
//        Code39Bean bean = new Code39Bean();
//        PDF417Bean bean=new PDF417Bean();
//        POSTNETBean bean =new POSTNETBean();
//        Interleaved2Of5Bean bean =new Interleaved2Of5Bean();
//        EAN128Bean bean =new EAN128Bean();
        Code128Bean bean = new Code128Bean();
        // 精细度
        final int dpi = 250;
        // module宽度
        final double moduleWidth = UnitConv.in2mm(2.0f / dpi);

        // 配置对象
        bean.setModuleWidth(moduleWidth);
//        bean.setWideFactor(3);
        bean.doQuietZone(false);

        String format = "image/png";
        try {
            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);
            // 生成条形码
            bean.generateBarcode(canvas, msg);
            // 结束绘制
            canvas.finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取条码输入流
     *
     * @param msg 条码信息
     * @return
     */
    public static ByteArrayInputStream generateToStream(String msg) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        generate(msg, ous);
        ByteArrayInputStream swapStream = new ByteArrayInputStream(ous.toByteArray());
        return swapStream;
    }

    public static void main(String[] args) {
        String msg = "123456789asdfxXW12";
        String path = "D:/barcode.png";
        generateFile(msg, path);
    }
}
